<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket测试</title>
</head>
<body>
    <div>
        <label for="">消息发送：
            <input type="text" id="messageText"/>
            <button type="button" id="sendBtn" onclick="sendMessage()">消息发送</button>
        </label>
    </div>
    <div>
        <label for="">响应内容：
            <textarea id="responseText" rows="100" cols="200"></textarea>
        </label>
    </div>
    <script>
        var socket;
        var res = document.getElementById("responseText");
        var req = document.getElementById("messageText");
        var sendBtn = document.getElementById("sendBtn");
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            // 8085 socket连接
            socket = new WebSocket("ws://localhost:8085/websocket");

            // 接收消息
            socket.onmessage = function(event) {
                res.value += event.data+"\n\r";
            };

            socket.onopen = function (event) {
                res.value = "打开WebSoket 服务正常，浏览器支持WebSoket!"+"\n\r";
            };

            socket.onerror = function (event) {
                console.log(event);
                alert("WebSocket连接失败");
            }

            socket.onclose = function(event) {
                res.value = "";
                res.value = "WebSocket 关闭"+"\n\r";
            };

        } else {
            alert("您的浏览器不支持WebSocket协议！");
        }

        // 发送消息
        function sendMessage() {
            if (!window.WebSocket) return;
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(req.value);
            } else {
                alert("WebSocket没有建立成功！");
            }
        };

    </script>
</body>
</html>